package com.ssl.unsafe;

import sun.misc.Unsafe;

import java.lang.reflect.Field;
import java.util.concurrent.CountDownLatch;

/**
 * 描述：
 *
 * @author ssl
 * @create 2021/7/13 0013.
 */
public class UnsafeDemo {

    private static Integer threadSize = 10;


    public static void main(String[] args) throws Exception {

        ValueEntity valueEntity = new ValueEntity();


        CountDownLatch latch = new CountDownLatch(threadSize);
        for (int i = 0; i < threadSize; i++) {
            new Thread(() -> {
                for (int j = 0; j < 10000; j++) {
                    valueEntity.inCre();
                }
                System.out.println(Thread.currentThread().getName() + "--->" + valueEntity.sum);
                latch.countDown();
            }, String.valueOf(i)).start();
        }
        latch.await();
        System.out.println("最终结果：sum = " + valueEntity.sum);
    }

    static class ValueEntity {
        private int sum = 0;

        private static Unsafe unsafe;
        private static long sum_offset;

        static {
            try {
                Field field = Unsafe.class.getDeclaredField("theUnsafe");
                field.setAccessible(true);
                unsafe = (Unsafe) field.get(null);
                sum_offset = unsafe.objectFieldOffset(ValueEntity.class.getDeclaredField("sum"));
            } catch (NoSuchFieldException | IllegalAccessException e) {
                e.printStackTrace();
            }
        }


        public void inCre() {
            while (unsafe.compareAndSwapInt(this, sum_offset, sum, sum++)) {
                sum++;
            }
            // return unsafe.getAndAddInt(this, sum_offset, 1) + 1;
        }
    }
}
